package com.gframework.core.dao;

import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;

import com.gframework.boot.flyway.IFlywayExtendSPI;

/**
 * 应用与flyway的数据库连接信息加载扩展接口，主要是对于常见spring数据源配置进行判断，但不保证一定能获取到，
 * 这与具体的使用者有关。
 * 
 * @author Ghwolf
 */
@Order(Integer.MIN_VALUE)
public class DbConnInfoLoadFlywaySPI implements IFlywayExtendSPI{

	// url
	private static final String[] URL_KEYS = new String[]{
			"spring.datasource.druid.url",
			"spring.datasource.url",
			"spring.datasource.hikari.jdbc-url",
	};
	// username
	private static final String[] USERNAME_KEYS = new String[]{
			"spring.datasource.druid.username",
			"spring.datasource.username",
			"spring.datasource.hikari.username",
	};
	// password
	private static final String[] PASSWORD_KEYS = new String[]{
			"spring.datasource.druid.password",
			"spring.datasource.password",
			"spring.datasource.hikari.password",
	};
	
	@Override
	public String getUrl(String currentUrl,Environment environment) {
		if (!StringUtils.isEmpty(currentUrl)) {
			return null ;
		}
		return get(URL_KEYS,environment);
	}
	
	@Override
	public String getUsername(String currentUsername, Environment environment) {
		if (!StringUtils.isEmpty(currentUsername)) {
			return null ;
		}
		return get(USERNAME_KEYS,environment);
	}
	
	@Override
	public String getPassword(String currentPassword, Environment environment) {
		if (!StringUtils.isEmpty(currentPassword)) {
			return null ;
		}
		return get(PASSWORD_KEYS,environment);
	}
	
	private String get(String[] arr,Environment environment){
		for (String k : arr) {
			String v = environment.getProperty(k);
			if (v != null) {
				return v;
			}
		}
		return null ;
	}
}
